package com.dyz.leetcode._15_BFSAndDFS;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

public class _590_postorder {
    //迭代
    public List<Integer> postorder1(Node root) {
        LinkedList<Integer> res = new LinkedList<>();
        if (root ==null) {return res;}

        Stack<Node> stack = new Stack<>();
        stack.push(root);

        while (!stack.isEmpty()) {
            Node curr = stack.pop();
            res.addFirst(curr.val);
            List<Node> children = curr.children;
            for (Node child : children) {
                stack.push(child);
            }
        }
        return res;
    }

    // 2. 递归
    public List<Integer> postorder(Node root) {
        List<Integer> res = new ArrayList<>();
        if (root ==null) {return res;}
        dfs(root, res);
        return res;
    }

    private void dfs(Node node, List<Integer> res) {
        if (node == null) {return;}
        for (Node child : node.children) {
            dfs(child, res);
        }
        res.add(node.val);
    }
}
